<template>
    <div class="imgList">
        <el-upload
        :before-upload="beforeAvatarUpload"
        accept="image/*,video/*"
        :action="action"
        :data="insertProgram"
        :on-success="uploadSuccess"
        class="avatar-uploader"
        :show-file-list="false">
        
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>

    </div>
</template>
<script>
export default {
    props:["data","id","index","dataField"],
    data(){
        return{
            imageUrl:"",
            action:"/business/api/file/fileUpload",
            pId:"",
            cId:"",
            insertProgram: {
                model: "",
                type:"",
                id:"",
                name:"",
                keyPId:"",
                token:sessionStorage.getItem("token")
            }
        }
    },
    created(){
        let ids=this.id.split(".");
        if(ids.length>1){
            this.pId=ids[0];
            this.cId=ids[1]
            
        }else if(this.dataField){
            this.pId=this.dataField;
            this.cId=this.id;
        }

        if(this.index=='0'||this.index){
            this.imageUrl=this.data[this.pId][this.index][this.cId]
        }else{
            this.imageUrl=this.data[this.pId][this.cId]
        }
    },
    methods:{
        beforeAvatarUpload(file) {
            let _this = this
            return new Promise((resolve, reject) => {
                
                let  isJPG = file.type.indexOf("image")!=-1||file.type.indexOf("video")!=-1;
               
                let isLt2M = file.size / 1024 / 1024 < 13 // 判定图片大小是否小于10MB
                let isLt2M2 = file.size / 1024 / 1024 > 3 // 判定图片大小是否小于10MB
                
                if(!isLt2M||!isJPG) {
                    reject()
                }
                if(file.type.indexOf("image")!=-1){
                    let image = new Image(), resultBlob = '';
                    image.src = URL.createObjectURL(file);
                    image.onload = () => {
                        if(isLt2M2){
                            console.log("需要压缩--------------------");
                            // 调用方法获取blob格式，方法写在下边
                            resultBlob = _this.compressUpload(image, file);
                            resolve(resultBlob)
                        }else{
                            console.log("不需要压缩--------------------");
                            resolve(file);
                        }
                        
                    }
                    image.onerror = () => {
                        reject()
                    }
                }else{
                    
                    resolve(file);
                }
                
            })
            /*
            const isJPG = file.type.indexOf("image")!=-1;
            const isLt2M = file.size / 1024 / 1024 < 10;

            if (!isJPG) {
                this.$message.error('只能上传图片!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 10MB!');
            }
            return isJPG && isLt2M;*/
        },
        uploadSuccess(response, file, fileList){
            this.uploaded(response);
            
            /*
            this.$emit('input',JSON.stringify(data));
            this.$emit('on-change',JSON.stringify(data));*/
            
        },
        uploaded(response){
            
            this.imageUrl=response[0].url;
            if(this.index=="0"||this.index){
                this.data[this.pId][this.index][this.cId]=response[0].url
            }else{
                this.data[this.pId][this.cId]=response[0].url
            }
            
            this.$message({
                message: '上传成功!',
                type: 'success'
            });
        },
        /* 图片压缩方法-canvas压缩 */
        compressUpload(image, file) {
            let canvas = document.createElement('canvas')
            let ctx = canvas.getContext('2d')
            let initSize = image.src.length
            let { width } = image, { height } = image
            canvas. width = width
            canvas.height = height
            ctx.fillRect(0, 0, canvas.width, canvas.height)
            ctx.drawImage(image, 0, 0, width, height)
            
            // 进行最小压缩0.1
            let compressData = canvas.toDataURL(file.type || 'image/jpeg', 0.5)
            
            // 压缩后调用方法进行base64转Blob，方法写在下边
            let blobImg = this.dataURItoBlob(compressData)
            return blobImg
        },
        
        /* base64转Blob对象 */
        dataURItoBlob(data) {
            let byteString;
            if(data.split(',')[0].indexOf('base64') >= 0) {
                byteString = atob(data.split(',')[1])
            }else {
                byteString = unescape(data.split(',')[1])
            }
            let mimeString = data
                .split(',')[0]
                .split(':')[1]
                .split(';')[0];
            let ia = new Uint8Array(byteString.length)
            for( let i = 0; i < byteString.length; i += 1) {
                ia[i] = byteString.charCodeAt(i)
            }
            return new Blob([ia], {type: mimeString})
        }
    }
}
</script>
<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
}
.avatar {
    width: 80px;
    height: 80px;
    display: block;
}
</style>